import os
import cv2
import numpy as np
import pyvirtualcam
from pyvirtualcam import PixelFormat
import threading
import queue
import time

# 视频源，可以是本地文件路径或流媒体地址
video_source = r"C:\Users\happy\Downloads\videoplayback.mp4"

# 初始化视频捕获
cap = cv2.VideoCapture(video_source)

if not cap.isOpened():
    print("无法打开视频源！")
    exit()

# 获取视频分辨率和帧率
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)

print(f"视频分辨率：{width}x{height}, 帧率：{fps}")


width = 1280
height = 720

# 定义帧队列以缓冲帧数据
frame_queue = queue.Queue(maxsize=10)

# 读取视频帧的线程
def read_frames():
    while True:
        start_time = time.time()  # 记录开始时间

        ret, frame = cap.read()
        if not ret:
            print("视频播放结束，重新开始...")
            cap.set(cv2.CAP_PROP_POS_FRAMES, 0)  # 重新播放
            continue

        # 将帧放入队列中
        if not frame_queue.full():
            frame_queue.put(frame)

        # 控制帧读取速度，匹配视频的实际帧率
        elapsed_time = time.time() - start_time
        time_to_wait = max(1.0 / fps - elapsed_time, 0)
        time.sleep(time_to_wait)

# 启动读取线程
read_thread = threading.Thread(target=read_frames, daemon=True)
read_thread.start()

# 使用 pyvirtualcam 发送帧到虚拟摄像头
with pyvirtualcam.Camera(width=width, height=height, fps=int(fps), fmt=PixelFormat.BGR) as cam:
    print(f"虚拟摄像头已启动：{cam.device}")

    while True:
        if not frame_queue.empty():
            frame = frame_queue.get()

            # 显示视频帧（可选）
            cv2.imshow("Video Stream", frame)

            # 将帧发送到虚拟摄像头
            cam.send(frame)
            cam.sleep_until_next_frame()

        # 按下 'q' 键退出
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

# 释放资源
cap.release()
cv2.destroyAllWindows()
